1. Hello World

Step into the world of R programming as you write your very first line of code. You will learn the concept of object assignment and use of functions.
Author

Nien Xiang Tou

Published

September 11, 2024

Image generated by generative AI.

Learning Goals

  • Learn how to create objects
  • Learn how to use functions

Write your first code

Click the Run Code button below to execute the following code. Try inputting your own message and re-run the code.

Create objects

R programming revolves around the concept of objects, which allows the storage of data, functions, and results in named objects that can be easily referenced and manipulated throughout our codes.

Objects can be created by assigning values using <-. In the example below, we created an object named message_object using a left assignment approach that stores a string variable “Hello World”.

If you call the object, it will generate the value assignment as an output.

You may also assign an object on the right to a value on the left with -> instead. Additionally, you may also use the equal sign = to assign the value on the right to the object on the left.

Naming objects - Take note!

Object names cannot include spacing thus underscore(s) or dot(s) are often used to connect multiple words. Also, object names cannot start with either a number of a dot followed by a number.

Exercise 1.1

Create two objects that contain one numeric value each.

R on its own can be used as a fancy scientific calculator, and we may easily apply math operations to numeric object variables. Here are some basic examples.

Functions

As the name suggests, functions are objects that contain a set of instructions to perform a specific task. Base R comes with a multitude of functions and we have used the print() function when we wrote our first code. Functions are often executed by passing required arguments within the parentheses.

In the example code below, the c() function is first used to concatenate a series of values into a data structure termed a vector and assigned to an object. The print() function was then used to print the object.

We may also execute a series of mathematical functions on the vector object.

Exercise 1.2

Create a vector object named num_vec using the c() function that contains at least ten numeric values.

Compute the mean, standard deviation, minimum, and maximum values of the vector, and assign them to the respective object names.

Object assignment facilitates reference management and efficiency in reusing them. For example, the code below generates a message output based on the objects created in the exercise.